// src/main/java/cn/edu/tju/elm/service/UserAuthorityService.java
package cn.edu.tju.elm.service;

import cn.edu.tju.core.model.User;
import cn.edu.tju.core.security.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserAuthorityService {
    
    @Autowired
    private UserRepository userRepository;

    /**
     * 根据用户ID获取用户权限名称集合
     */
    public Set<String> getUserAuthorities(Long userId) {
        User user = getUserByIdWithAuthorities(userId);
        
        return user.getAuthorities().stream()
                .map(authority -> authority.getName())
                .collect(Collectors.toSet());
    }
    
    /**
     * 根据用户ID获取用户实体（包含权限信息）
     */
    public User getUserByIdWithAuthorities(Long userId) {
        return userRepository.findOneWithAuthoritiesById(userId)
                .orElseThrow(() -> new IllegalArgumentException("用户不存在: " + userId));
    }
    
    /**
     * 检查用户是否具有商家权限
     */
    public boolean isMerchant(Long userId) {
        Set<String> authorities = getUserAuthorities(userId);
        return authorities.contains("ROLE_MERCHANT") || 
               authorities.contains("MERCHANT");
    }
    
    /**
     * 检查用户是否具有管理员权限
     */
    public boolean isAdmin(Long userId) {
        Set<String> authorities = getUserAuthorities(userId);
        return authorities.contains("ROLE_ADMIN");
    }
    
    /**
     * 检查用户是否具有普通用户权限
     */
    public boolean isRegularUser(Long userId) {
        Set<String> authorities = getUserAuthorities(userId);
        return authorities.contains("ROLE_USER") && !isMerchant(userId);
    }
    
    /**
     * 检查用户是否具有特定权限
     */
    public boolean hasAuthority(Long userId, String authority) {
        Set<String> authorities = getUserAuthorities(userId);
        return authorities.contains(authority);
    }
    
    /**
     * 根据用户ID获取用户实体（不包含权限信息）
     */
    public User getUserById(Long userId) {
        return userRepository.findById(userId)
                .orElseThrow(() -> new IllegalArgumentException("用户不存在: " + userId));
    }
}